# coding=utf-8

"""
Description：yield生成器案例
"""
import time

"""
斐波那契数列：1,1,2,3,5,8,13,21,34,55,89,144
从数列的第三项开始，后面每一项是前面两项之和

数学上的定义：F(0) = 1, F(1) = 1, F(n) = F(n-1) + F(n-2)(n>=2, n∈N)
"""


# 普通的斐波那契数列实现
def fab1(max):
    n, a, b = 0, 0, 1
    while n < max:
        # print('->', b)
        a, b = b, a + b

        n = n + 1


# 生成器算法实现斐波那契数列
def fab2(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b  # 使用yield生成器
        a, b = b, a + b

        n = n + 1


def test():
    # 最大迭代数
    max_num = 10000
    start_time = time.time()
    fab1(max_num)
    end_time = time.time()
    print('fab1 total time %.2f' % (1000 * (end_time - start_time)), 'ms')

    start_time = time.time()
    b = fab2(max_num)
    print(b)
    end_time = time.time()
    print('fab2 total time %.2f' % (1000 * (end_time - start_time)), 'ms')


if __name__ == '__main__':
    test()
